package com.book.auth.service.impl;

import com.book.core.domain.SysMenu;
import com.book.core.domain.SysRole;
import com.book.core.enums.CommonStatus;
import com.book.core.mode.SysLoginUser;
import com.book.core.domain.SysUser;
import com.book.service.SysMenuService;
import com.book.service.SysRoleService;
import com.book.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SysUserDetailsService implements UserDetailsService {
    private final SysUserService sysUserService;
    private final SysRoleService sysRoleService;
    private final SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser one = sysUserService.lambdaQuery().eq(SysUser::getUserName, username).one();
        if (one == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
//        查询角色信息
        List<String> roleCodeList = sysRoleService.getRoleCodeListByUserId(one.getUserId());
        boolean is = sysRoleService.isAdmin(one.getUserId());
        List<String> menList;
        if (is) {
            menList = sysMenuService.lambdaQuery().eq(SysMenu::getStatus, CommonStatus.NORMAL.getCode()).list().stream().map(SysMenu::getMenuCode).collect(Collectors.toList());
        } else {
            menList = sysMenuService.getMenuCodeListByUserId(one.getUserId());
        }
        return new SysLoginUser(one, roleCodeList, menList);
    }
}
